package com.mynews.activities.sign;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.google.android.material.snackbar.Snackbar;
import com.mynews.activities.App;
import com.mynews.bean.User;
import com.mynews.databinding.ActivitySignBinding;
import com.mynews.utils.BmobApi;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class SignVM extends AndroidViewModel {
    public static MutableLiveData<String> nickname=new MutableLiveData<>(),account=new MutableLiveData<>(),password=new MutableLiveData<>(),password2=new MutableLiveData<>(),email=new MutableLiveData<>();
    @SuppressLint("StaticFieldLeak")
    private static SignActivity signActivity;

    public SignVM(@NonNull Application application) {
        super(application);
        nickname.setValue("");
        account.setValue("");
        password.setValue("");
        password2.setValue("");
        email.setValue("");
    }
    public void sign(View view){
        if (nickname.getValue().equals("")){
            Snackbar.make(view,"请选填写昵称",Snackbar.LENGTH_SHORT).show();
            return;
        }
        if (account.getValue().equals("")){
            Snackbar.make(view,"请选填写账号",Snackbar.LENGTH_SHORT).show();
            return;
        }
        if (password.getValue().equals("")){
            Snackbar.make(view,"请选填写密码",Snackbar.LENGTH_SHORT).show();
            return;
        }
        if (password2.getValue().equals("")){
            Snackbar.make(view,"请再次填写密码",Snackbar.LENGTH_SHORT).show();
            return;
        }
        if (email.getValue().equals("")){
            Snackbar.make(view,"请选填写邮箱，用于找回密码",Snackbar.LENGTH_SHORT).show();
            return;
        }
        if (password.getValue().equals(password2.getValue())){
            JSONObject json=new JSONObject();
            try {
                json.put("username",account.getValue());
                json.put("password",password.getValue());
                json.put("email",email.getValue());
                json.put("nickname",nickname.getValue());
                json.put("isAdmin",false);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            BmobApi.post(json, "https://api2.bmob.cn/1/users", new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                }
                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    JSONObject jo1;
                    try {
                        assert response.body() != null;
                        jo1 = new JSONObject(response.body().string());
                       if (jo1.isNull("error")){
                           App.user=new User(email.getValue(),jo1.getString("sessionToken"), jo1.getString("objectId"),account.getValue(),nickname.getValue(),false);

                           SharedPreferences.Editor edit = App.sp.edit();
                            edit.putString("account",account.getValue());
                            edit.putString("password",password.getValue());
                            edit.apply();
                           BmobApi.post(new JSONObject().put("email", email.getValue()), "https://api2.bmob.cn/1/requestEmailVerify", new Callback() {
                               @Override
                               public void onFailure(@NotNull Call call, @NotNull IOException e) {
                                   signActivity.setResult(2);
                                   signActivity.runOnUiThread(() -> Toast.makeText(signActivity,"验证邮件发送失败"+e.getMessage(),Toast.LENGTH_SHORT).show());
                                   signActivity.finish();
                               }
                               @Override
                               public void onResponse(@NotNull Call call, @NotNull Response response) {
                                   signActivity.setResult(2);
                                   signActivity.runOnUiThread(() -> Toast.makeText(signActivity,"已发送邮件，请尽快验证",Toast.LENGTH_SHORT).show());
                                   signActivity.finish();
                               }
                           });
                       }else {
                           signActivity.runOnUiThread(() -> {
                               try {
                                   Toast.makeText(signActivity, "注册失败"+jo1.getString("error"), Toast.LENGTH_SHORT).show();
                               } catch (JSONException e) {
                                   e.printStackTrace();
                               }
                           });
                       }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }else {
            Snackbar.make(view,"两次密码不一样",Snackbar.LENGTH_SHORT).show();
        }
    }
    public void setBinding(SignActivity signActivity) {
        SignVM.signActivity=signActivity;
        signActivity.setResult(1);
    }
}
